package com.ncs.cns.business.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class SafeSimpleDateFormat
{
	private static SafeSimpleDateFormat globleFormat;
	public static SafeSimpleDateFormat getInstance(){
		if(globleFormat==null){
			createInstance();
		}
		return globleFormat;
	}
	private static synchronized SafeSimpleDateFormat createInstance(){
		if(globleFormat==null){
			globleFormat = new SafeSimpleDateFormat();
		}
		return globleFormat;
	}
	private SafeSimpleDateFormat(){
	}
	
    private static final ThreadLocal _dateFormats = new ThreadLocal()
    {
        public Object initialValue()
        {
            return new HashMap();
        }
    };

    private SimpleDateFormat getDateFormat(String format)
    {
        Map<String, SimpleDateFormat> formatters = (Map)_dateFormats.get();
        SimpleDateFormat formatter = formatters.get(format);
        if (formatter == null)
        {
            formatter = new SimpleDateFormat(format);
            formatters.put(format, formatter);
        }
        return formatter;
    }

    public String format(String format,Date date,String defaultFormat)
    {
    	if(format ==null){
    		return getDateFormat(defaultFormat).format(date);
    	}
        return getDateFormat(format).format(date);
    }

 
    public Date parse(String format , String day) throws ParseException
    {
        return getDateFormat(format).parse(day);
    }
}
